const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : `0${n}`;
};

const formatTime = (date) => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`;
};

// 复制到本地临时路径，方便预览
const getLocalUrl = (path, name) => {
  const fs = wx.getFileSystemManager();
  const tempFileName = `${wx.env.USER_DATA_PATH}/${name}`;
  fs.copyFileSync(path, tempFileName);
  return tempFileName;
};

const secondsToHourMinuteSecond = (seconds) => {
  const hours = Math.floor(seconds / 3600); // 计算小时
  const mins = Math.floor((seconds % 3600) / 60); // 计算分钟
  const secs = seconds % 60; // 计算秒数

  const paddedMins = String(mins).padStart(2, '0');
  const paddedSecs = String(secs).padStart(2, '0');

  // 如果小时为 0，去掉小时部分
  if (hours === 0 && mins === 0) {
    return `${paddedSecs}`; // 只显示秒
  }

  // 如果小时为 0，去掉小时部分
  if (hours === 0) {
    return `${paddedMins}:${paddedSecs}`; // 只显示分:秒
  }

  // 否则，显示时:分:秒
  return `${String(hours).padStart(2, '0')}:${paddedMins}:${paddedSecs}`;
}

function findLastElement(data, currentTime, getTime) {
  let left = 0;
  let right = data.length - 1;
  let result = null;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    const midTime = getTime(data[mid]);

    if (midTime <= currentTime) {
      result = data[mid];
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  return result;
}

function formatTimeBySec(sec) {
  const m = Math.floor(sec / 60)
  const s = Math.floor(sec % 60)
  return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
}

function callFunctionWithRetry(name, data = {}, maxRetries = 3, delay = 500) {
  return new Promise((resolve, reject) => {
    let attempt = 0

    const tryCall = () => {
      wx.cloud.callFunction({ name, data })
        .then(res => resolve(res))
        .catch(err => {
          attempt++
          if (attempt < maxRetries) {
            console.warn(`调用失败，重试第 ${attempt} 次...`)
            setTimeout(tryCall, delay)
          } else {
            reject(err)
          }
        })
    }

    tryCall()
  })
}

module.exports = {
  formatTimeBySec,
  getLocalUrl,
  secondsToHourMinuteSecond,
  findLastElement,
  formatTime,
  callFunctionWithRetry
};